package org.summerframework.component.mybatisplus;


import com.baomidou.mybatisplus.core.metadata.IPage;
import org.summerframework.core.exception.WebException;
import org.summerframework.core.page.PageResult;
import org.summerframework.core.page.PaginationHelper;
import org.summerframework.core.page.PaginationQuery;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * @author shichao
 */
@Slf4j
public class PaginationPlusHelper {
    /**
     * @param records 记录
     * @return 结果
     */
    public static <D> PageResult<D> fetchPage(IPage<D> records) {
        long totalPage = 1;
        long count = records.getTotal();
        long size = records.getSize();

        totalPage = count / size;

        if ((count == 0) || ((count % size) != 0)) {
            totalPage++;
        }

        PageResult<D> result = new PageResult<>();
        result.setPageSize(size);
        long current = records.getCurrent();
        result.setPageIndex(current);
        result.setStartRow((size * (current - 1)));
        result.setTotalItem(count);
        result.setTotalPage(totalPage);
        result.setData(records.getRecords());
        return result;
    }

    /**
     * @param records  记录
     * @param query    查询条件
     * @param function 转换function
     * @return 结果
     * @deprecated {@link #fetchPage(IPage, Function)}
     */
    @Deprecated
    public static <T, D> PageResult<T> fetchPage(IPage<D> records, PaginationQuery query, Function<D, T> function) {
        return PaginationHelper.fetchPage(Long.valueOf(records.getTotal()).intValue(), query, records.getRecords().stream().map(function).collect(Collectors.toList()));
    }

    /**
     * @param records  记录
     * @param function 转换function
     * @return 结果
     */
    public static <T, D> PageResult<T> fetchPage(IPage<D> records, Function<D, T> function) throws WebException {
        long totalPage = 1;
        long count = records.getTotal();
        long size = records.getSize();

        totalPage = count / size;

        if ((count == 0) || ((count % size) != 0)) {
            totalPage++;
        }

        PageResult<T> result = new PageResult<>();
        result.setPageSize(size);
        long current = records.getCurrent();
        result.setPageIndex(current);
        result.setStartRow((size * (current - 1)));
        result.setTotalItem(count);
        result.setTotalPage(totalPage);
        result.setData(records.getRecords().stream().map(function).collect(Collectors.toList()));
        return result;
    }
}
